package com.luckku.boot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.luckku.boot.common.api.ApiResult;
import com.luckku.boot.common.exception.ApiAsserts;
import com.luckku.boot.jwt.JwtUtil;
import com.luckku.boot.utils.MD5Utils;
import com.luckku.boot.entity.User;
import com.luckku.boot.mapper.UserMapper;
import com.luckku.boot.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Luckku
 * @since 2022-10-09
 */
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public User executeRegister(User user) {
        //查询是否有相同用户名的用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserAccount, user.getUserAccount());
        User haveUser = baseMapper.selectOne(wrapper);
        if (!ObjectUtils.isEmpty(haveUser)) {
            ApiAsserts.fail("账号已存在！");
        }
        User addUser = User.builder()
                .userAccount(user.getUserAccount())
                .userPwd(MD5Utils.getPwd(user.getUserPwd()))
                .userName(user.getUserName())
                .userSchool(user.getUserSchool())
                .userMajor(user.getUserMajor())
                .build();
        baseMapper.insert(addUser);

        return addUser;
    }


        @Override
        public Map<String, String> executeLogin(User user) {
            Map<String, String> map = new HashMap<>(16);

            QueryWrapper<User> queryWrapper = new QueryWrapper();
            queryWrapper.lambda().eq(User::getUserAccount, user.getUserAccount())
                    .eq(User::getUserPwd, MD5Utils.getPwd(user.getUserPwd()));
            User exist = baseMapper.selectOne(queryWrapper);
            if (ObjectUtils.isEmpty(exist)) {
                return map;
            }
            String token = JwtUtil.generateToken(String.valueOf(user.getUserAccount()));
            map.put("token", token);
            map.put("userId",exist.getUserId().toString());
            map.put("userName",exist.getUserName());
            map.put("userAccount",exist.getUserAccount());
            map.put("userSchool",exist.getUserSchool());
            map.put("userMajor",exist.getUserMajor());
            map.put("photoUrl",exist.getPhotoUrl());
            return map;
        }



    @Override
    public User getUserById(String userId) {
        return baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUserId, userId));
    }
}
